<template>
  <div class="app-container">
    <!-- 查询参数及按钮部分 -->
    <div class="button">
      <div class="filter-container">
        <!-- <el-button
          size="small"
          class="filter-item"
          type="primary"
          style="margin-left: 10px;"
        >
          导出模板
        </el-button> -->
        <!-- <el-button
          size="small"
          class="filter-item"
          type="primary"
          style="margin-left: 10px;"
        >
          导出
        </el-button>
        <el-button
          size="small"
          class="filter-item"
          type="primary"
          style="margin-left: 10px;"
        >
          导入
        </el-button> -->
        <el-button size="small" class="filter-item" type="primary" style="margin-left: 10px;" @click="handleAdd">
          新增
        </el-button>
        <el-button size="small" class="filter-item" type="primary" @click="handleEdit">
          修改
        </el-button>
        <!--<el-button-->
        <!--size="small"-->
        <!--class="filter-item"-->
        <!--type="primary"-->
        <!--:loading="removeBtnLoading"-->
        <!--@click="handleRemove" >-->
        <!--删除-->
        <!--</el-button>-->
        <el-button size="small" class="filter-item" type="primary" :loading="saveBtnLoading" @click="handleSave">
          保存
        </el-button>
      </div>
    </div>
    <!-- 表格部分 -->
    <el-table ref="singalTable" v-loading="listLoading" :data="list" :stripe="true" :height="tableHeight" fit
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
      <template slot="empty">
        <tableEmpty />
      </template>
      <el-table-column type="selection" align="center" width="55" />
      <el-table-column type="index" align="center" width="80" label="序号" />
      <el-table-column label="工资项名称" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-input v-model="row.salaryName" maxlength="60" placeholder="请输入" />
          </div>
          <span v-else>{{ row.salaryName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate && row.salaryCode !== 's1' && row.salaryCode !== 's2'">
            <el-select v-model="row.baseState" placeholder="请选择">
              <el-option v-for="item in dict.baseState" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <span v-else>{{ row.baseState | dictFilter('baseState', that) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否标准项" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-select v-model="row.isStandard" placeholder="请选择">
              <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <span v-else>{{ row.isStandard | dictFilter('yesOrNo', that) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否计算项" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-select v-model="row.isCompute" placeholder="请选择">
              <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <span v-else>{{ row.isCompute | dictFilter('yesOrNo', that) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="工资项类型" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-select v-model="row.computeFormula" placeholder="请选择">
              <el-option v-for="item in dict.withNo" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <span v-else>{{ row.computeFormula | dictFilter('withNo', that) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="月结是否清零" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-select v-model="row.isClear" placeholder="请选择">
              <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <span v-else>{{ row.isClear | dictFilter('yesOrNo', that) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否代扣项" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-select v-model="row.isAccsalPay" placeholder="请选择">
              <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <span v-else>{{ row.isAccsalPay | dictFilter('yesOrNo', that) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否代缴项" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-select v-model="row.isAccsalWithhold" placeholder="请选择">
              <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <span v-else>{{ row.isAccsalWithhold | dictFilter('yesOrNo', that) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否显示" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-select v-model="row.isShow" placeholder="请选择">
              <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <span v-else>{{ row.isShow | dictFilter('yesOrNo', that) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否校验功能分类" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-select v-model="row.isCheck" placeholder="请选择">
              <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <span v-else>{{ row.isCheck | dictFilter('yesOrNo', that) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="小数位数" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-input-number v-model="row.decimalPlace" style="width: 100%;" controls-position="right" :min="0"
              :max="10" :step="1" step-strictly />
          </div>
          <span v-else>{{ row.decimalPlace }}</span>
        </template>
      </el-table-column>
      <el-table-column label="显示顺序" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-input-number v-model="row.showOrder" style="width: 100%;" controls-position="right" :min="1" :max="1000"
              :step="1" step-strictly />
          </div>
          <span v-else>{{ row.showOrder }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工资条顺序" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-input-number v-model="row.salaryListOrder" style="width: 100%;" controls-position="right" :min="1"
              :max="1000" :step="1" step-strictly />
          </div>
          <span v-else>{{ row.salaryListOrder }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isOperate">
            <el-input v-model="row.remark" maxlength="10" placeholder="请输入" />
          </div>
          <span v-else>{{ row.remark }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!--分页部分-->
    <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import {
  queryPage,
  submitData,
  deleteBatchData,
  submitSalaryBasedata
} from '@/api/salaryConfigManage/salaryProjectMaintenance'
import Pagination from '@/components/Pagination'
import tableEmpty from '@/components/table/empty'

export default {
  name: 'SalaryProjectMaintenance',
  components: {
    Pagination,
    tableEmpty
  },
  filters: {
    dictFilter(value, dictType, that) {
      const dict = that.dict[dictType]
      for (const item of dict) {
        if (value === item.value) {
          return item.label
        }
      }
    }
  },
  data() {
    return {
      tableHeight: null,
      that: this,
      submitIds: [],
      submitList: [],
      flag: '',
      submitArr: [],//判断是否为非法非扣
      addItem: {
        id: '',
        salaryName: '',
        baseState: '1',
        isStandard: 0,
        isCompute: 0,
        isCheck: 0,//是否校验功能分类
        isClear: 0,
        isAccsalPay: 0,
        isAccsalWithhold: 0,
        isShow: 1,
        decimalPlace: '',
        remark: '',
        isOperate: true,
        isNewItem: ''
      },
      list: [],
      total: 0,
      listLoading: true,
      removeBtnLoading: false,
      saveBtnLoading: false,
      listQuery: {
        page: 1,
        limit: 200
      },
      dict: {
        baseState: [
          { label: '启用', value: '1' },
          { label: '停用', value: '0' }
        ],
        yesOrNo: [{ label: '是', value: 1 }, { label: '否', value: 0 }],
        withNo: [{ label: '发项', value: 1 }, { label: '扣项', value: -1 }, { label: '非发非扣', value: 0 }]
      }
    }
  },
  computed: {
    ids() {
      const selection = this.$refs.singalTable.selection
      const arr = []
      selection.forEach(item => {
        if (!item.isNewItem) {
          arr.push(item.id)
        }
      })
      return arr.join(',')
    }
  },
  watch: {
    list(val) {
      this.doLayout()
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },

  methods: {
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 204
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    getList() {
      this.listLoading = true
      queryPage(this.listQuery)
        .then(response => {
          this.list = response.data.rows
          this.total = response.data.total
          this.listLoading = false
          this.initData()
        })
        .catch(() => {
          this.initData()
        })
    },

    initData() {
      this.submitIds = []
      this.submitList = []
    },

    handleAdd() {
      // this.$confirm('工资项名称只能填写汉字或英文小括号！', '提示', {
      //   closeOnClickModal: false,
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      this.flag = 'add'
      const addItem = { ...this.addItem }
      addItem.isNewItem = Math.random()
        .toString(16)
        .substr(2, 8)
      this.list.unshift(addItem)
      this.submitList.push(addItem)
      // })
    },

    handleEdit() {
      const selection = this.$refs.singalTable.selection
      this.flag = 'edit'
      // if (selection.length !== 1) {
      //   this.$message({
      //     message: '请选择一条数据',
      //     type: 'warning',
      //     showClose: true,
      //     duration: 4000
      //   })
      //   return
      // }

      // if (selection[0].salaryCode==='s1'|| selection[0].salaryCode==='s2') {
      //       this.$message({
      //         message: '实发、应发工资不可修改',
      //         type: 'warning',
      //         showClose: true,
      //         duration: 4000
      //       })
      //       return
      //     }

      // this.$confirm('工资项名称只能填写汉字或英文小括号！', '提示', {
      //   closeOnClickModal: false,
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      // 避免多次点击编辑按钮，导致出现重复数据
      if (!this.submitIds.includes(selection[0].id)) {
        for (let i = 0; i < selection.length; i++) {
          this.$set(selection[i], 'isOperate', true)
        }
        this.submitIds.push(selection[0].id)
        this.submitList = selection
      }
      // })
    },

    handleRemove() {
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        this.$message({
          message: '请选择至少一条数据',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        return
      }
      for (const select of selection) {
        if (
          select.id === '46F1370C5F2A4D31AD196718A93DC470' ||
          select.id === '3C4B5B347C9F420BB8D4B86572A5F178'
        ) {
          this.$message({
            message: '应发项和实发工资不可删除',
            type: 'warning',
            showClose: true,
            duration: 4000
          })
          return
        }
      }
      this.removeBtnLoading = true
      this.$confirm('确定删除吗？', '提示', {
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 删除新增的数据
          this.removeNewItem(selection)
          // 删除数据库中的数据
          if (this.ids) {
            deleteBatchData(this.ids)
              .then(() => {
                this.$message({
                  message: '删除成功',
                  type: 'success',
                  showClose: true,
                  duration: 4000
                })
                this.handleFilter()
                this.removeBtnLoading = false
              })
              .catch(() => {
                this.removeBtnLoading = false
              })
          } else {
            this.removeBtnLoading = false
          }
        })
        .catch(() => {
          this.removeBtnLoading = false
        })
    },

    removeNewItem(selection) {
      const newItemArr = []
      selection.forEach(item => {
        if (item.isNewItem) {
          newItemArr.push(item.isNewItem)
        }
      })
      if (newItemArr.length > 0) {
        const list = this.list
        for (let i = 0; i < list.length; i++) {
          if (newItemArr.indexOf(list[i].isNewItem) > -1) {
            list.splice(i--, 1)
          }
        }
        const submitList = this.submitList
        for (let i = 0; i < submitList.length; i++) {
          if (newItemArr.indexOf(submitList[i].isNewItem) > -1) {
            submitList.splice(i--, 1)
          }
        }
      }
    },

    handleSave() {
      const submitList = this.submitList

      if (submitList.length === 0) {
        this.$message({
          message: '没有可保存的数据',
          type: 'warning',
          showClose: true,
          duration: 2000
        })
        return
      }
      for (const item of submitList) {
        if (!item.salaryName) {
          this.$message({
            message: '工资项名称为必填项',
            type: 'warning',
            showClose: true,
            duration: 2000
          })
          return
        }
        if (item.computeFormula === "" || item.computeFormula === null || item.computeFormula === undefined) {

          this.$message({
            message: '工资项类型为必填项',
            type: 'warning',
            showClose: true,
            duration: 2000
          })
          return
        }
        if (item.computeFormula != 0) {
          this.submitArr.push(item.computeFormula)
        }

        // else {
        //   const regex = /^[\u4e00-\u9fa5]*\(?[\u4e00-\u9fa5]*\)?[\u4e00-\u9fa5]*$/
        //   if (!regex.test(item.salaryName)) {
        //     this.$message({
        //       message: '工资项名称只能填写汉字或英文小括号！',
        //       type: 'warning',
        //       showClose: true,
        //       duration: 2000
        //     })
        //     return
        //   }
        // }
      }
      this.saveBtnLoading = true

      if (submitList.salaryListOrder === '') {
        submitList.salaryListOrder = null
      }
      submitData(submitList)
        .then(response => {
          this.submitSalaryBasedata()
        })
        .catch(() => {
          this.saveBtnLoading = false
        })


    },
    // 如三个都是非法非扣不需要走该方法
    submitSalaryBasedata() {

      if (this.flag === 'add' && this.submitArr.length === 0) {
        this.$message({
          message: '保存成功',
          type: 'success',
          showClose: true,
          duration: 2000
        })
        this.handleFilter()
        this.saveBtnLoading = false
        return
      }

      submitSalaryBasedata()
        .then(response => {
          this.$message({
            message: '保存成功',
            type: 'success',
            showClose: true,
            duration: 2000
          })
          this.handleFilter()
          this.saveBtnLoading = false
        })

    },
    selectable(row) {
      // 实发项和应发项复选框disable，不允许修改
      //   if (row.id == '0'|| row.code !=='0') { return false }{ return true}
      if (row.salaryCode === 's2') {
        return false;
      }
      if (row.salaryCode === 's1') {
        return false;
      } else {
        return true;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-title {
  margin-bottom: 15px;
  height: 20px;
  border-bottom: 1px solid #dcdfe6;
}

.button {
  float: right;
}

/** 文本框高度 **/
::v-deep .el-input {
  width: auto !important;
}
</style>
